package io.github.talelin.latticy.service;

import io.github.talelin.autoconfigure.exception.ForbiddenException;
import io.github.talelin.autoconfigure.exception.NotFoundException;
import io.github.talelin.latticy.common.CommonUtil;
import io.github.talelin.latticy.common.UserUtil;
import io.github.talelin.latticy.dto.VacationDTO;
import io.github.talelin.latticy.entity.Vacation;
import io.github.talelin.latticy.repository.VacationRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Optional;

@Service
public class VacationService {

    @Autowired
    private VacationRepository vacationRepository;

    @Autowired
    private RecordService recordService;

    @Autowired
    private UserUtil userUtil;

    @Transactional
    public void create(VacationDTO dto) {
        Vacation vacation = new Vacation();
        Date now = new Date();
        Long userId = UserUtil.getCurrentUserId();
        Long rootUserId = userUtil.getRootUserId();
        BeanUtils.copyProperties(dto, vacation);
        vacation.setUserId(userId);
        vacation.setStatus(1);
        vacation.setCreateTime(now);
        vacation.setStartTime(CommonUtil.stringToDate2(dto.getStartTime()));
        vacation.setEndTime(CommonUtil.stringToDate2(dto.getEndTime()));
        vacationRepository.save(vacation);
        //同步记录
        recordService.create(userId, dto.getExamineUserId(), rootUserId, 1, vacation.getId());
    }

    public void updateStatus(Long id, int status) {
        Vacation vacation = this.get(id);
        vacation.setStatus(status);
        vacationRepository.save(vacation);
    }

    public Vacation get(Long id) {
        Optional<Vacation> vacation = vacationRepository.findById(id);
        return vacation.orElseThrow(() -> new NotFoundException());
    }

    @Transactional
    public void updated(Long id, VacationDTO dto) {
        Vacation vacation = this.get(id);
        if (vacation.getStatus() == 3) {
            throw new ForbiddenException(20006);
        }
        BeanUtils.copyProperties(dto, vacation);
        vacation.setStartTime(CommonUtil.stringToDate2(dto.getStartTime()));
        vacation.setEndTime(CommonUtil.stringToDate2(dto.getEndTime()));
        vacation.setStatus(1);
        vacationRepository.save(vacation);
        //同步记录
        recordService.updateStatusToWait(1, vacation.getId());
    }
}
